package com.hltx.controller.user;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hltx.controller.base.BaseController;
import com.hltx.pojo.common.Page;
import com.hltx.pojo.smscode.SmsCodeValidate;
import com.hltx.pojo.user.User;
import com.hltx.pojo.user.UserLogin;
import com.hltx.service.order.OrderManager;
import com.hltx.service.picture.PictureManager;
import com.hltx.service.smscode.impl.SmsCodeValidateService;
import com.hltx.service.user.UserManager;
import com.hltx.util.CustomUtil;
import com.hltx.util.MD5Util;
import com.hltx.util.MessagesCode;
import com.hltx.util.ResultInfo;
import com.hltx.util.sms.code.NeteaseSms;


/**
 * 用户controller
 * 
 * @author shibeilei
 *
 */
@Controller
@RequestMapping("/user")
@Component
public class UserController extends BaseController{

	@Resource(name="userService")
	private UserManager userService;
	
	@Resource(name="orderService")
	private OrderManager orderService;
	
	@Resource(name="PictureService")
	private PictureManager PictureService;
	
	@Value("${FTP_BASE_PATH}")
	private String FTP_BASE_PATH;
	
	@Value("${domain}")
	private String domain;
	
	@Resource(name ="smsCodeValidateService")
	private SmsCodeValidateService smsCodeValidateService;
	/**
	 * 打开个人中心
	 */
	@RequestMapping
	public String index(HttpSession session , HttpServletRequest request,Page page) {
		User u = (User) session.getAttribute("sessionUser");
		page.getParams().put("userid",u.getId());
		Map<String, Object> stateCount=orderService.getStateCount(page);
		request.setAttribute("stateCount", stateCount);
		User user = userService.getUser(u);
		if(user.getPetName() == null){
			String petName =user.getPhone().substring(0, 3)+"****"+user.getPhone().substring(user.getPhone().length()-4, user.getPhone().length());
			user.setPetName(petName);
		}
		String codePre = user.getCodePre();
		String codeSuf = user.getCodeSuf();
		String loginId = user.getId()+"";   
		String vipcode = codePre+loginId+codeSuf;  //定义用户唯一的标识 用于二维码和邀请
		session.setAttribute("vipcode", vipcode);
		request.setAttribute("user", user);
		request.setAttribute("domain", domain);
		return "user/personal_center";
	}
	/**
	 * 打开个人设置
	 * @throws Exception 
	 */
	@RequestMapping("/toSet")
	public String toSet(HttpSession session,HttpServletRequest request) throws Exception {
		User user = (User) request.getSession().getAttribute("sessionUser");
		String payPwd=userService.getPayPwd(user);
		request.setAttribute("payPwd", payPwd);
		return "user/set";
	}
	/**
	 * 回到首页
	 */
	@RequestMapping("/index")
	public String toIndex() {
		return "index";
	}
	@RequestMapping("/tofriend")
	public String tofriend() {
		return "user/invite_friends";
	}
	/**
	 * 打开手机设置
	 */
	@RequestMapping("/toModifyPhone")
	public String toModifyPhone(HttpServletRequest request,HttpSession session) {
		User user = (User) session.getAttribute("sessionUser");
		request.setAttribute("user", user);
		return "user/modifyPhone";
	}
	/**
	 * 电话号校验
	 */
	@RequestMapping("/checkphone")
	@ResponseBody
	public Map<String, Object> checkphone(HttpServletRequest request,HttpServletResponse response,@RequestParam Map<String, Object> params)throws Exception {
		this.logBefore(logger, "电话号校验");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{
		String userName = (String) params.get("phone");
		UserLogin userLogin=new UserLogin();
		userLogin.setUserName(userName);
		if(null!=userLogin){
			int count=userService.findByPhone(userLogin);
			if(count==0){
				resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", "success"));	
			}else{
				resMap.put("result", this.initResult(ResultInfo.ERROR, "error", "failed"));
			}
		}
		}catch(Exception e){
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "error", "error"));
			return resMap;
		}
		this.logAfter(logger);
		return resMap;
	}
	/**
	 * 打开登陆密码修改
	 */
	@RequestMapping("/toModifyPwd")
	public String toModifyPwd(HttpServletRequest request,HttpSession session) {
		User u = (User) session.getAttribute("sessionUser");
		User us = new User();
		us.setId(u.getId());
		User user = userService.getUser(us);
		request.setAttribute("user", user);
		System.out.println("userpwd"+user.getPwd());
		return "user/modifypwd";
	}
	/**
	 * 密码校验
	 */
	@RequestMapping("/checkPwd")
	@ResponseBody
	public Map<String, Object> checkPwd(HttpServletRequest request,HttpServletResponse response,@RequestParam Map<String, Object> params)throws Exception {
		this.logBefore(logger, "校验密码");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{
		String pwd = (String) params.get("pwd");
		String oldPwd = (String) params.get("oldPwd");
		oldPwd=MD5Util.MD5(oldPwd);
		if(pwd.equals(oldPwd)){
			resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", "success"));
		}
		}catch(Exception e){
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "error", "failed"));
			return resMap;
		}
		this.logAfter(logger);
		return resMap;
	}
	/**
	 * 密码修改
	 */
	@RequestMapping("/submitPwd")
	@ResponseBody
	public Map<String, Object> submitPwd(HttpServletRequest request,HttpServletResponse response,@RequestParam Map<String, Object> params)throws Exception {
		this.logBefore(logger, "保存密码");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{
		String newPwd = (String) params.get("newPwd");
		String oldPwd = (String) params.get("oldPwd");
		User user = (User) request.getSession().getAttribute("sessionUser");
		Integer id = user.getLoginId();
		String userName = user.getPhone();
		String result=userService.updatePwd(id, oldPwd, newPwd,userName);
		if("1".equals(result)){
			resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", "修改成功"));
		}else if("2".equals(result)){
			resMap.put("result", this.initResult(ResultInfo.ERROR, "error", "修改失败"));	
		}else if("3".equals(result)){
			resMap.put("result", this.initResult(ResultInfo.ERROR, "err", "密码修改失败请及时联系我们!"));
		}
		}catch(Exception e){
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "error", "修改失败"));
			return resMap;
		}
		this.logAfter(logger);
		return resMap;
	}
	/**
	 * 验证码
	 */
	@RequestMapping("/getCode")
	public void getCode(HttpServletRequest request,HttpServletResponse response,@RequestParam Map<String, Object> params)throws Exception {
		System.out.println("得到验证码");
		PrintWriter out = null;
		response.setCharacterEncoding("utf-8");
		out = response.getWriter();
		int code = CustomUtil.buildRandom(4);
		out.print(code);
	}
	/**
	 * 手机修改
	 */
	@RequestMapping("/submitPhone")
	@ResponseBody
	public Map<String, Object> submitPhone(HttpServletRequest request,HttpServletResponse response,@RequestParam Map<String, Object> params)throws Exception {
		this.logBefore(logger, "保存手机");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{
		String phone = (String) params.get("phone");
		User user = (User) request.getSession().getAttribute("sessionUser");
		Integer id = user.getId();
		userService.updatePhone(id,phone);
		user.setPhone(phone);
		request.getSession().setAttribute("sessionUser", user);
		resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", "保存成功"));
		}catch(Exception e){
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.SUCCESS, "error", "保存失败"));
			return resMap;
		}
		this.logAfter(logger);
		return resMap;
		
	}
	@RequestMapping("/toSetup")
	public String toSetup(HttpSession session,HttpServletRequest request) {
		User u = (User) session.getAttribute("sessionUser");
		//int id = u.getId();
		User user = userService.getUser(u);
		request.setAttribute("user", user);
		return "user/setup";
	}
	@RequestMapping("/toModify")
	public String toModify() {
		return "user/modify";
	}
	@RequestMapping("/saveName")
	@ResponseBody
	public Map<String, Object> saveName(HttpSession session,HttpServletRequest request,HttpServletResponse response,@RequestParam Map<String, Object> params)throws Exception {
		this.logBefore(logger, "保存昵称");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{
		String petName = (String) params.get("name");
		User user = (User) session.getAttribute("sessionUser");
		Integer id = user.getId();
		userService.saveName(id,petName);
		resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", "保存成功"));
		}catch(Exception e){
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.SUCCESS, "error", "保存失败"));
			return resMap;
		}
		this.logAfter(logger);
		return resMap;
	}
	
	@RequestMapping("/upSex")
	@ResponseBody
	public Map<String, Object> upSex(HttpSession session,HttpServletRequest request,HttpServletResponse response,@RequestParam Map<String, Object> params)throws Exception{
		this.logBefore(logger, "保存性别");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{
		String sex = (String) params.get("sex");
		User user = (User) session.getAttribute("sessionUser");
		Integer id = user.getId();
		userService.updateSex(id,sex);
		resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", "保存成功"));
		}catch(Exception e){
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.SUCCESS, "error", "保存失败"));
			return resMap;
		}
		this.logAfter(logger);
		return resMap;
	}
	@RequestMapping("/upBirthday")
	@ResponseBody
	public Map<String, Object> upBirthday(HttpSession session,HttpServletRequest request,HttpServletResponse response,@RequestParam Map<String, Object> params)throws Exception{
		this.logBefore(logger, "保存生日");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{
			String birthday = (String) params.get("birthday");
			User user = (User) session.getAttribute("sessionUser");
			Integer id = user.getId();
			userService.updateDay(id,birthday);
			resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", "保存成功"));
		}catch(Exception e){
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.SUCCESS, "error", "保存失败"));
			return resMap;
		}
		this.logAfter(logger);
		return resMap;
	}
	@SuppressWarnings("rawtypes")
	@RequestMapping("/uploadImg")
	@ResponseBody
	public Map<String, Object> uploadImg(HttpSession session,HttpServletRequest request,HttpServletResponse response,@RequestParam Map<String, Object> params)throws Exception{
		this.logBefore(logger, "保存头像");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{
			String strBase64 = (String) params.get("base64Image");
			User u = (User) session.getAttribute("sessionUser");
			Integer id = u.getId();
			User user = userService.getUser(u);
			String codePre = user.getCodePre();
			String codeSuf = user.getCodeSuf();
			String path ="/personal"+"/"+codePre+id+codeSuf;
			Map imagePath=PictureService.uploadPicture(strBase64, path, "head.png");
			int error = (int) imagePath.get("error");
			if(error == 0){
			String imageAddress = (String) imagePath.get("url")+"?v" + CustomUtil.buildRandom(4);
			userService.uploadimageAddress(id,imageAddress);
			resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", "保存成功"));
			resMap.put("imageAddress", this.initResult(ResultInfo.SUCCESS, "ok", imageAddress+"?r="+CustomUtil.buildRandom(4)));
			}else{
			resMap.put("result", this.initResult(ResultInfo.ERROR, "error", "保存失败"));
			}
		}catch(Exception e){
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "error", "保存失败"));
			return resMap;
		}
		this.logAfter(logger);
		return resMap;
	}
	
	/**
	 * 获取支付密码
	 */
	@RequestMapping("/getPayPwd")
	@ResponseBody
	public Map<String, Object> getPayPwd(HttpServletRequest request,HttpServletResponse response)throws Exception {
		this.logBefore(logger, "获取支付密码");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{
		User user = (User) request.getSession().getAttribute("sessionUser");
		String payPwd=userService.getPayPwd(user);
		resMap.put("payPwd", payPwd);
		resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", "获取成功"));
		}catch(Exception e){
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "error", "系统繁忙"));
			return resMap;
		}
		this.logAfter(logger);
		return resMap;
	}
	
	/**
	 * 修改支付密码
	 */
	@RequestMapping("/updatePayPwd")
	@ResponseBody
	public Map<String, Object> updatePayPwd(HttpServletRequest request,HttpServletResponse response,String pwd)throws Exception {
		this.logBefore(logger, "保存支付密码");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{
		if(StringUtils.isEmpty(pwd)){
			resMap.put("result", this.initResult(ResultInfo.ERROR, "error", "修改失败"));
			return resMap;
		}
		User user = (User) request.getSession().getAttribute("sessionUser");
		Integer id = user.getLoginId();
		userService.updatePayPwd(id, MD5Util.MD5Encode(pwd, "utf-8"));
		resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", "修改成功"));
		}catch(Exception e){
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "error", "修改失败"));
			return resMap;
		}
		this.logAfter(logger);
		return resMap;
	}
	
	/**
	 * 打开支付密码设置页面
	 */
	@RequestMapping("/toSetPayPwd")
	public String toModifyPayPwd(HttpServletRequest request,HttpSession session) {
		User u = (User) session.getAttribute("sessionUser");
		User us = new User();
		us.setId(u.getId());
		User user = userService.getUser(us);
		request.setAttribute("user", user);
		System.out.println("userpwd"+user.getPwd());
		return "user/setPayPwd";
	}
	/**
	 * 打开支付密码修改页面
	 */
	@RequestMapping("/toUpdatePayPwd")
	public String toUpdatePayPwd(HttpServletRequest request,HttpSession session) {
		User u = (User) session.getAttribute("sessionUser");
		User us = new User();
		us.setId(u.getId());
		User user = userService.getUser(us);
		request.setAttribute("user", user);
		System.out.println("userpwd"+user.getPwd());
		return "user/modifyPayPwd";
	}
	/**
	 * 修改支付密码前验证手机
	 */
	@RequestMapping("/toCheckPhone")
	public String toCheckPhone(HttpServletRequest request,HttpSession session) {
		User user = (User) session.getAttribute("sessionUser");
		request.setAttribute("user", user);
		return "user/modifyPayPwd_first";
	}
	@ResponseBody
	@RequestMapping("/send")
	public Map<String, Object> send(HttpServletResponse response,HttpServletRequest request){
		this.logBefore(logger, "发送短信验证码");
		Map<String, Object> resMap = new HashMap<String, Object>();
		String mobile = request.getParameter("phone");
		if(mobile != null){
			logBefore(logger, mobile);
			//发送短信
			SmsCodeValidate sms = new SmsCodeValidate();
			sms.setPhone(mobile);
			sms.setTypes(request.getParameter("type"));
			try {
				SmsCodeValidate validate = smsCodeValidateService.getSmsData(sms);
				if(validate == null){
					//Long nowTime= System.currentTimeMillis() ;
					sms.setExpireTime("60");
					String code =CustomUtil.buildRandom(6)+"";
					sms.setCode(code);
					sms.setSendNum(0);
					//发送短信线程
					resMap.put("code", code);
					resMap.put("sendNum", 0);
					int i= smsCodeValidateService.saveSmsCode(sms);
					if(i>=1){
						NeteaseSms.sendTemplateSms(mobile, code);
						resMap.put("result", this.initResult(ResultInfo.SUCCESS, MessagesCode.SUCCESS, "60"));
					}else{
						resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "短信入库异常"));
					}
				}else{
					SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd"); 
					String date = format.format(new Date());
					String date_time= validate.getCreateTime();
					date_time = date_time.substring(0, 10).replace("-", "").trim();
					if (validate.getSendNum()>=3 && !date.equals(date_time)) {
						validate.setSendNum(-1);
						smsCodeValidateService.intiSmsData(validate);
					}
					if (validate.getSendNum()<3) {
						if (Long.valueOf(validate.getExpireTime()) < System.currentTimeMillis()) {
							Long IntervalTime = (long) (validate.getSendNum()<2?60:1800);
							sms.setExpireTime(IntervalTime.toString());
							String code =CustomUtil.buildRandom(6)+"";
							sms.setCode(code);
							smsCodeValidateService.updateSmsCode(sms);
							NeteaseSms.sendTemplateSms(mobile, code);
							resMap.put("code", code);
							resMap.put("sendNum", validate.getSendNum());
							resMap.put("result", this.initResult(ResultInfo.SUCCESS, MessagesCode.SUCCESS, IntervalTime.toString()));
						}else{
							resMap.put("result", this.initResult(ResultInfo.SUCCESS, MessagesCode.SUCCESS, " "));
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				this.logError(logger, e.getMessage());
				resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
			}
		}else{
			resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.HPONE_ISNULL, "手机号码不能为空!"));
		}
		this.logAfter(logger);
		return resMap;
	}
	private String validateCode(HttpServletRequest request) {
		String  msg = "ok";
		String phone = request.getParameter("phone");
		String code = request.getParameter("code");
		String types = request.getParameter("type");
		SmsCodeValidate sms = new SmsCodeValidate();
		sms.setPhone(phone);
		sms.setCode(code);
		sms.setTypes(types);
		try {
			SmsCodeValidate validate = smsCodeValidateService.getSmsCode(sms);
			if(validate != null){
				SmsCodeValidate scv = smsCodeValidateService.getSmsIsExpire(sms);
				if (scv == null) {
					msg ="expire";
				}
			}else{
				msg = "error";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return msg;
	}

	/**
	 * 验证验证码是否正确
	 * @param user
	 * @param response
	 * @param request	
	 * @return
	 */
	@ResponseBody
	@RequestMapping( value = "/checkcode")
	public Map<String, Object>  checkcode(@ModelAttribute User user,HttpServletResponse response,HttpServletRequest request){
		this.logBefore(logger, "验证");
		Map<String, Object> map = new HashMap<>();
		String msg = validateCode(request);
		if ("ok".equals(msg)) {
			map.put("result", this.initResult(ResultInfo.SUCCESS, "ok", MessagesCode.SUCCESS));
		}else if("expire".equals(msg)){
			map.put("result", this.initResult(ResultInfo.SUCCESS, "expire", MessagesCode.VALIDATE_EORROR));
		} else{
			map.put("result", this.initResult(ResultInfo.SUCCESS, "error", MessagesCode.VALIDATE_EORROR));
		}
		this.logAfter(logger);
		return map;
	}
}
